<?php

namespace App\Admin\Controllers\Account;


use App\Admin\Models\AdminPaytypeList;
use App\Admin\Models\Financial\FinancialMoneylog;
use App\Admin\Models\SiteStoreContract;
use App\Admin\Services\Financial;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Models\SiteStore;
use App\Common\Services\Admin\Common as AdminCommon;

use Illuminate\Support\Facades\DB;

class StoreContractController extends Controller
{
    /**
     * 获取详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteStore::with(['companyinfo', 'adminuserinfo', 'businessmeminfo'])->where(['id' => $id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $info->store_file_path = json_decode($info->store_file_path, true);
        $info->contract_file_path = json_decode($info->contract_file_path, true);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 获取列表
     */
    public function getcontractlist(Request $request)
    {
        $list = SiteStoreContract::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 新增合同数据
     * 1.获取新增 数据
     * 2.根据id获取 获取原门店信息补充字段
     * 3.新增完成，并写入门店表id
     * {"id":7,"contract_at":"2024-11-22 00:00:00","contract_end_at":"2024-11-30",
     * "pay_at":"2024-11-14","soft_year_fee":67700,"contract_type":1,"pay_type":2,
     * "pay_type_name":"微信支付","business_mem_id":3,"remark":"remak2","contract_file_path":[]}
     *
     *
     */
    public function docontractadd(Request $request)
    {
        // 公司id 门店id  合同签订时间  合同到期时间 支付时间  合同到期时间 业务员编号 合同图片
        $data = $request->post();
        if (empty($data['id'])) {
            return response()->json(['code' => '001', 'msg' => '数据异常']);
        }

        $data['store_relation_id'] = $data['id'];

        $data['contract_at'] = $this->timeToStr($data['contract_at']);
        $data['contract_end_at'] = $this->timeToStr(($data['contract_end_at'] . ' 23:59:59'));
        $data['pay_at'] = $this->timeToStr($data['pay_at']);
        $data['pay_type'] =  empty($data['pay_type']) ? 0:$data['pay_type'];
        $data['pay_type_name'] = $data['pay_type_name'] ?? '';
        $data['business_mem_id'] = empty($data['business_mem_id'])?0:$data['business_mem_id'];

        if ($data['contract_end_at'] <= time()) {
            return response()->json(['code' => '001', 'msg' => '合同续期时间异常']);
        }

        if (empty($data['contract_type'])) {
            return response()->json(['code' => '001', 'msg' => '合同类别不能为空']);
        }
//        if(empty($data['business_mem_id'])){
//            return response()->json(['code' => '001', 'msg' => '业务员id不能为空']);
//        }

        $data['create_at'] = time();
        $data['update_at'] = time();
        //contract_audit_status 1待审核，2审核中，3审核成功，4审核失败
        $data['contract_audit_status'] = 2; //提交成功直接提交审核
        $data['admin_user_id'] = AdminCommon::getCurrentAdminId($request);
        /**
         *补全数据，获取cp_id,address_area,store_name,contact_name
         *  contact_phone,customer_service_id
         * */
        $storeInfo = \App\Store\Models\Account\SiteStore::where('id', $data['id'])->first();
        if (empty($storeInfo)) {
            return response()->json(['code' => '001', 'msg' => '数据异常']);
        }
        $data['cp_id'] = $storeInfo['cp_id'];
        $data['address_area'] = $storeInfo['address_area'];
        $data['store_name'] = $storeInfo['store_name'];

        $data['contact_name'] = $storeInfo['contact_name'];
        $data['contact_phone'] = $storeInfo['contact_phone'];
        $data['customer_service_id'] = $storeInfo['customer_service_id'];
        $data['contract_file_path'] = is_array($data['contract_file_path']) ? json_encode($data['contract_file_path']) : json_encode(is_array(json_decode($data['contract_file_path'], true)) ? json_decode($data['contract_file_path'], true) : []);

        unset($data['id']);
        //dd($data);
        $contract = SiteStoreContract::create($data);
        if ($contract->id > 0) {
            return response()->json(['code' => '000', 'msg' => '合同添加成功']);
        } else {
            return response()->json(['code' => '001', 'msg' => '合同添加失败']);
        }

    }

    public function timeToStr($data)
    {
        if (!$data) {
            return 0;
        }
        $strtotime_time = strtotime($data);
        if ($strtotime_time > 0) {
            return $strtotime_time;
        } else {
            return intval($data);
        }
    }

    /**
     * 合同审核
     */
    public function docontractaudit(Request $request)
    {
        /*
         *  合同审核需要同步主表数据
         *  'contract_audit_status' => 3, 'update_at' => time();
         *  1待审核，2审核中，3审核成功，4审核失败
         * */
        $id = $request->id ?? 0;
        $contract_audit_status = $request->contract_audit_status ?? 0;
        if (!$id) {
            return response()->json(['code' => '001', 'msg' => 'id不存在']);
        }
        if (!in_array($contract_audit_status, ['3', '4'])) {
            return response()->json(['code' => '001', 'msg' => '非法请求']);
        }
        if ($contract_audit_status == '4') {
            $res = SiteStoreContract::where('id', $id)->update(['contract_audit_status' => 4, 'update_at' => time()]);
            if ($res > 0) {
                return response()->json(['code' => '000', 'msg' => '合同取消成功']);
            } else {
                return response()->json(['code' => '001', 'msg' => '合同取消失败']);
            }
        }
        /***
         *
         *  "soft_year_fee" => "689"
         * "contract_at" => 1732896000
         * "contract_end_at" => 1732896000
         * "pay_at" => 1730390400
         * "pay_type" => "3"
         * "pay_type_name" => "银行卡"
         * "contract_type" => "1"
         * "business_mem_id" => "3"
         * "contract_file_path" => "[]"
         * "remark" => "remakr3"
         * "update_at" => 1731465693
         * "store_file_path" => "[]"
         * "contract_audit_status" => 2
         * */
        $info = SiteStoreContract::where('id', $id)->first();
        $storeData = [];
       // $storeData['soft_year_fee'] = $info['soft_year_fee'];
        $storeData['contract_at'] = $info['contract_at'];
        $storeData['contract_end_at'] = $info['contract_end_at'];
        $storeData['pay_at'] = $info['pay_at'];
        $storeData['pay_type'] = $info['pay_type'];
        $storeData['pay_type_name'] = $info['pay_type_name'];
        $storeData['contract_type'] = $info['contract_type'];
        $storeData['business_mem_id'] = $info['business_mem_id'];
        $storeData['contract_file_path'] = $info['contract_file_path'];
        $storeData['remark'] = $info['remark'];
        $storeData['update_at'] = $info['update_at'];
        $storeData['contract_audit_status'] = 3;
        $storeData['is_can_use'] = 1;

        // 日记账
        $moneyLog = [];
        $payInfo = AdminPaytypeList::where(['id' => $info['pay_type']])->first();
        $payName = !empty($payInfo) ? $payInfo->pay_type_name : '';
        $paytype = !empty($payInfo) ? $payInfo->type : 1;
        //1现金、2银行、3储蓄卡
        if (strpos($payName, '现金') !== false || $paytype == 3) {
            $moneyLog['type'] = 1;
            $receipt = '现收';
        } else {
            $moneyLog['type'] = 2;
            $receipt = '银记';
        }
        $moneyLog['inout_type'] = 2;
        $moneyLog['log_date'] = date('Y-m-d', time());
        $moneyLog['pay_type_id'] = $info['pay_type'];
        $moneyLog['receipt_type'] = 1;
        $moneyLog['abstract'] = '合同ID' . $info['id'];
        // 销售收入
        $moneyLog['subject_id'] = -1;
        $moneyLog['income_money'] = $info['soft_year_fee'];
        $moneyLog['create_at'] = time();
        $moneyLog['update_at'] = $moneyLog['create_at'];
        $financial = Financial::getmoneylogcount($moneyLog['type'], $moneyLog['receipt_type']);
        $moneyLog['receipt_no'] = $receipt . ($financial['no'] ?? '');

        $last_moneylog = FinancialMoneylog::where(['type' => $moneyLog['type'], 'is_del' => 1])->orderBy('id', 'desc')->first();
        $last_moneylog_residue_money = !empty($last_moneylog) ? $last_moneylog->residue_money : 0;
        $moneyLog['residue_money'] = $last_moneylog_residue_money +  $moneyLog['income_money'];

        DB::beginTransaction();
        try {

            SiteStoreContract::where('store_relation_id', $info['store_relation_id'])->update(['contract_audit_status' => 4, 'update_at' => time(), 'is_valid' => 1]);
            SiteStoreContract::where('id', $id)->update(['contract_audit_status' => 3, 'update_at' => time(), 'is_valid' => 2]);
            SiteStore::where('id', $info['store_relation_id'])->update($storeData);
            //  增加日记账
            FinancialMoneylog::query()->create($moneyLog);
            DB::commit();
            return response()->json(['code' => '000', 'msg' => '操作成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败']);
        }


    }

    /*
     *  主门店数据迁移
     *  合同迁移
     *
     *
    */
    public function docontractmigration(Request $request)
    {
        $sitestore = SiteStore::where('is_del', 1)->get()->toArray();
        $insertData = [];
        if (!empty($sitestore)) {
            //获取合同表数据是否存在
            $store_ids = SiteStoreContract::where('is_del', 1)->pluck('store_relation_id')->toArray();

            foreach ($sitestore as $item) {
                if (in_array($item['id'], $store_ids)) {
                    continue;
                }
                $row = [];
                $row['business_mem_id'] = $item['business_mem_id'];
                $row['contract_at'] = $item['contract_at'];
                $row['contract_end_at'] = $item['contract_end_at'];
                $row['contract_file_path'] = $item['contract_file_path'];
                $row['contract_type'] = $item['contract_type'];
                $row['pay_at'] = $item['pay_at'];
                $row['pay_type'] = $item['pay_type'];
                $row['pay_type_name'] = $item['pay_type_name'];
                $row['remark'] = $item['remark'];
                $row['soft_year_fee'] = $item['soft_year_fee'];
                $row['store_relation_id'] = $item['id'];
                $row['create_at'] = $item['create_at'];
                $row['update_at'] = $item['update_at'];
                $row['contract_audit_status'] = $item['contract_audit_status'];
                $row['admin_user_id'] = $item['admin_user_id'];
                $row['cp_id'] = $item['cp_id'];
                $row['address_area'] = $item['address_area'];
                $row['store_name'] = $item['store_name'];
                $row['contact_name'] = $item['contact_name'];
                $row['contact_phone'] = $item['contact_phone'];
                $row['customer_service_id'] = $item['customer_service_id'];
                $insertData[] = $row;
            }

            if (!empty($insertData)) {
                SiteStoreContract::insert($insertData);
                return response()->json(['code' => '000', 'msg' => '操作成功']);
            } else {
                return response()->json(['code' => '001', 'msg' => '数据已迁移']);
            }
        }

    }
}
